#!/usr/bin/env python
import time
import datetime
import re

class Time(object):
    
    time_fmt='%Y-%m-%d %X'
    
    @staticmethod
    def timestamp():
        return time.time()
    
    @staticmethod
    def date_fmt(sep='-'):
        return sep.join(['%Y','%m','%d'])
    
    @staticmethod
    def now():
        return time.strftime(Time.time_fmt,time.localtime(time.time()))
    
    @staticmethod
    def today(sep='-'):
        fmt=Time.date_fmt(sep)
        return time.strftime(fmt,time.localtime(time.time()))
    
    @staticmethod
    def yesterday(sep='-'):
        fmt=Time.date_fmt(sep)
        return time.strftime(fmt,time.localtime(time.time()-24*60*60))
    
    @staticmethod
    def tomorrow(sep='-'):
        fmt=Time.date_fmt(sep)
        return time.strftime(fmt,time.localtime(time.time()+24*60*60))
        
    @staticmethod
    def is_date(date):
        try:
            date=str(date)
        except Exception:
            return False
        m=re.compile(r'^(?:\d{4})(?:[^\d]+)?(?:\d{2})(?:[^\d]+)?(?:\d{2})$').match(date)
        if m:
            return True
        return False
    
    @staticmethod
    def date_format(date,sep='-'):
        if not Time.is_date(date):
            return Time.yesterday(sep)
        m=re.compile(r'^(\d{4})([^\d]+)?(\d{2})([^\d]+)?(\d{2})$').match(str(date))
        if m:
            return sep.join(m.group(1,3,5))
        else:
            return Time.yesterday(sep)
        
    @staticmethod
    def date_sep(date):
        sep=''
        m=re.compile(r'^(?:\d{4})([^\d]+)?(?:\d{2})([^\d]+)?(?:\d{2})$').match(str(date))
        if m:
            sep1,sep2=m.group(1) or sep,m.group(2) or sep
            assert sep1==sep2,"Date '%s''s seperator is not the same." % date
            return sep1
        return sep
        
    @staticmethod
    def _date_action(date,action='+',itv=1):
        date=str(date)
        sep=Time.date_sep(date)
        fmt=Time.date_fmt(sep)
        if action=='+':
            return time.strftime(fmt,time.localtime(time.mktime(time.strptime(date,fmt))+itv*24*60*60))
        elif action=='-':
            return time.strftime(fmt,time.localtime(time.mktime(time.strptime(date,fmt))-itv*24*60*60))
        else:
            return date
        
    @staticmethod
    def date_add(date,itv=1):
        return Time._date_action(date,'+',itv)
    
    @staticmethod
    def date_sub(date,itv=1):
        return Time._date_action(date,'-',itv)
    
    @staticmethod
    def last_week(date):
        return Time.date_sub(date,itv=6)
        
    @staticmethod
    def last_month(date):
        return Time.date_sub(date,itv=29)
        
    @staticmethod
    def last_year(date):
        return Time.date_sub(date,itv=364)
    
    @staticmethod
    def last_hour():
        return time.strftime('%H',time.localtime(time.time()-60*60))
        
    @staticmethod
    def is_hour(hour):
        try:
            int(hour)
        except Exception:
            return False
        hour=int(hour)
        if hour>=0 and hour<=23:
            return True
        return False
    
    @staticmethod
    def hour_format(hour):
        m=re.match('^(\d{1,2})$',str(hour))
        if m:
            h=m.group(1)
            if int(h)<10:
                return '0'+str(h)
            else:
                return h
        else:
            return self.last_hour()
    
    @staticmethod
    def _time(time_str,fmt='%Y'):
        sth=time.strftime(fmt,time.localtime(time.mktime(time.strptime(time_str,Time.time_fmt))))
        if fmt=='%Y':
            return sth
        elif fmt=='%m' or fmt=='%d':
            return int(sth)
        elif fmt=='%W':
            return int(sth)+1
        elif fmt=='%w':
            if sth=='0':
                sth=7
            return sth
        else:
            return sth
    
    @staticmethod
    def time_year(time_str):
        return Time._time(time_str,fmt='%Y')
    
    @staticmethod
    def time_month(time_str):
        return Time._time(time_str,fmt='%m')
    
    @staticmethod
    def time_day(time_str):
        return Time._time(time_str,fmt='%d')
    
    @staticmethod
    def time_week(time_str):
        return Time._time(time_str,fmt='%w')
    
    @staticmethod
    def time_year_week(time_str):
        return Time._time(time_str,fmt='%W')
        
    @staticmethod
    def time_year_month(time_str,sep=''):
        fmt=sep.join(['%Y','%m'])
        return Time._time(time_str,fmt=fmt)
    
    @staticmethod
    def _date(date,fmt='%Y'):
        sep=Time.date_sep(date)
        date_fmt=Time.date_fmt(sep)
        sth=time.strftime(fmt,time.localtime(time.mktime(time.strptime(str(date),date_fmt))))
        if fmt=='%Y':
            return sth
        elif fmt=='%m' or fmt=='%d':
            return int(sth)
        elif fmt=='%W':
            return int(sth)+1
        elif fmt=='%w':
            if sth=='0':
                sth=7
            return sth
        else:
            return sth
        
    @staticmethod
    def date_year(date):
        return Time._date(date,'%Y')
    
    @staticmethod
    def date_month(date):
        return Time._date(date,'%m')
    
    @staticmethod
    def date_day(date):
        return Time._date(date,'%d')
    
    @staticmethod
    def date_week(date):
        return Time._date(date,'%w')
    
    @staticmethod
    def date_year_month(date,sep=''):
        fmt=sep.join(['%Y','%m'])
        return Time._date(date,fmt)
    
    @staticmethod
    def date_year_week(date):
        return Time._date(date,'%W')
   
    @staticmethod 
    def str2time(time_str):
        try:
            if Time.is_date(time_str):
                fmt=Time.date_fmt(sep='-')
            else:
                fmt=Time.time_fmt
            return time.mktime(time.strptime(time_str,fmt))
        except:
            return 0   
     
    @staticmethod
    def nginx_time(time,fmt='%d/%b/%Y:%H:%M:%S'):
        return str(datetime.datetime.strptime(time,fmt))
        
    @staticmethod
    def cst_time(time,fmt='%a %b %d %H:%M:%S CST %Y'):
        return str(datetime.datetime.strptime(time,fmt))
    
    @staticmethod
    def time2str(time_stamp):
        return time.strftime(Time.time_fmt,time.localtime(float(time_stamp)))
    
if __name__ == '__main__':
    print Time.timestamp()
    t=Time()
    today=Time.today()
    print t.date_format(today,sep='')
    print t.last_month(today)
    print t.time_week(t.now())
    print t.str2time(t.now())
    print t.time2str(1356422633)
    print t.nginx_time('22/Feb/2013:00:04:21')
    print t.is_date('2013/05/27')
    print t.time_year_month(t.now())
    print t.cst_time("Mon Jul 22 10:14:01 CST 2013")
    print t.date_year_month(20130731)
    print t.date_sep('2013-07-27')
    print t.date_add(20130730,3)
    
